package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

public class UpdaterRedisLock implements ILock {

    private String keyName;
    private static final String KEY_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";
    private StringRedisTemplate stringRedisTemplate;

    public UpdaterRedisLock(String keyName, StringRedisTemplate stringRedisTemplate) {
        this.keyName = keyName;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 尝试获取锁
     *
     * @param timeoutSec
     * @return
     */
    @Override
    public boolean tryLock(long timeoutSec) {
        // 获取当前线程标识
        String value = ID_PREFIX + Thread.currentThread().getId();
        // 尝试获取锁
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + keyName, value, timeoutSec, TimeUnit.SECONDS);
        // 防止自动拆箱出现空指针异常
        return Boolean.TRUE.equals(flag);
    }

    /**
     * 释放锁
     */
    @Override
    public void unlock() {
        // 获取当前线程标识
        String value = ID_PREFIX + Thread.currentThread().getId();
        // 获取锁中的标识
        String redisValue = stringRedisTemplate.opsForValue().get(KEY_PREFIX + keyName);
        // 判断标识是否一致，防止误删其他线程的锁
        if (value.equals(redisValue)) {
            stringRedisTemplate.delete(KEY_PREFIX + keyName);
        }
    }
}
